﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace open.xdjsclub.com_Web.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home

        /// <summary>
        /// 联合登录到签到页面
        /// </summary>
        /// <param name="Target"></param>
        /// <param name="StoreId"></param>
        /// <param name="Uid"></param>
        /// <param name="UnionId"></param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public ActionResult UnionVisit(string Target, string StoreId, string Uid, string UnionId, string sign)
        {
             ViewBag.Target = Target;
            ViewBag.StoreId = StoreId;
            ViewBag.Uid = Uid;
            ViewBag.UnionId = UnionId;
            ViewBag.Sign = sign;


            var existUnionUserSecret = Framework.Utilities.GetAppSettings("Union_" + UnionId);

            if (string.IsNullOrWhiteSpace(existUnionUserSecret))
            {
                ViewBag.Info = "未知的联盟用户ID";
                return View("ErrorUnion");

            }


            var list = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("Target", Target));
            list.Add(new KeyValuePair<string, string>("StoreId", StoreId));
            list.Add(new KeyValuePair<string, string>("Uid", Uid));
            list.Add(new KeyValuePair<string, string>("UnionId", UnionId));

            var signByCompute = GenerateSign(list, existUnionUserSecret);

            ViewBag.Before = GetParamBeforMD5(list, existUnionUserSecret);

            if (sign != signByCompute)
            {
                ViewBag.Info = "参数签名不合法：" + signByCompute;
                return View("ErrorUnion");

            }

            var phone = GetUserPhoneByUserId(Uid);
            if (string.IsNullOrWhiteSpace(phone))
            {
                ViewBag.Info = "用户ID无效：未能通过用户ID查询到用户手机号";
                return View("ErrorUnion");
            }

            phone = Framework.Utilities.EncryptDES(phone);
            phone = Server.UrlEncode(phone);
            if (Target.ToLower() == "normalsign")
            {
                Response.Redirect($"http://fuwu.xdjsclub.com/Sign/Union?fid={phone}&storeid={StoreId}&client={UnionId}");
                return null;
            }
            else
                return View("UnionVisit");
        }

        public ActionResult UnionVistIndex(string UserInfo, string UnionId, string sign)
        {
            ViewBag.UserInfo = UserInfo;
            ViewBag.UnionId = UnionId;
            ViewBag.sign = sign;
            UnionId = UnionId.Replace("pihui", "puhui");

            var list = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("UserInfo", UserInfo));
            list.Add(new KeyValuePair<string, string>("UnionId", UnionId));

            var existUnionUserSecret = Framework.Utilities.GetAppSettings("Union_" + UnionId);
            var signByCompute = GenerateSign(list, existUnionUserSecret);



            if (sign != signByCompute && sign != "nosign")
            {
                ViewBag.Info = "参数签名不合法：" + signByCompute;
                return View("");

            }
            else
                ViewBag.Info = "";

            GoToPageFroUnion(UnionId, UserInfo);
            //  Response.Redirect($"http://www.xdjsclub.com/tp.html");
            ViewBag.Info = UserInfo;
            return View("EmptyPage");
        }

        public ActionResult EmptyPage()
        {
            return View();
        }

        public string GetUserPhoneByUserId(string userId)
        {
            var jsonRst = Get($"https://api.cdzg028.com/labor-user/users/{userId}");

            if (!jsonRst.Contains("phoneNumber"))
                return "";
            var jsonObject = JObject.Parse(jsonRst);

            return JObject.Parse(jsonObject["data"]?.ToString())["phoneNumber"].ToString();




        }


        public string GetUserPhoneByPuhuiToken(string token)
        {
            return GetUserKeyValueByPuhuiToken(token, "mobile");
            //try
            //{
            //    var heads = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("token", token) };
            //    // var jsonRst = GetUrl($"https://test.cdzghome.com:8100/getUserInfo",heads);  测试环境地址


            //    var jsonRst = GetUrl(Framework.Utilities.GetAppSettings("puhui_tokenSer"), heads);   //预生产环境


            //    if (!jsonRst.Contains("mobile"))
            //        return "";
            //    var jsonObject = JObject.Parse(jsonRst);

            //    return JObject.Parse(jsonObject["data"]?.ToString())["mobile"].ToString();
            //}
            //catch (Exception ex)
            //{
            //    return "";
            //}
        }

        //mobile

        public string GetUserKeyValueByPuhuiToken(string token,string key)
        {
            try
            {
                var heads = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("token", token) };
                // var jsonRst = GetUrl($"https://test.cdzghome.com:8100/getUserInfo",heads);  测试环境地址


                var jsonRst = GetUrl(Framework.Utilities.GetAppSettings("puhui_tokenSer"), heads);   //预生产环境


                if (!jsonRst.Contains(key))
                    return "";
                var jsonObject = JObject.Parse(jsonRst);

                return JObject.Parse(jsonObject["data"]?.ToString())[key].ToString();
            }
            catch (Exception ex)
            {
                return "";
            }
        }


        public static string Get(string apiUrl)
        {
            return GetUrl(apiUrl, null);
        }

        public static string Get(string apiUrl, List<KeyValuePair<string, string>> headers)
        {

            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(apiUrl);   //创建WebRequest
            webRequest.Method = "get";    //get请求方法
                                          //webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("admin:admin")));  //添加授权信息，此项目不需要授权
                                          //获取返回信息



            if (apiUrl.Substring(0, 8) == "https://")
            {
                webRequest.ProtocolVersion = HttpVersion.Version10;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
            }

            if (headers != null && headers.Count > 0)
            {
                foreach (var item in headers)
                {
                    webRequest.Headers.Add(item.Key, item.Value);
                }

            }


            WebResponse webResponse = webRequest.GetResponse();
            Stream stream = webResponse.GetResponseStream();
            var streamReader = new StreamReader(stream, Encoding.UTF8);
            var response = streamReader.ReadToEnd();
            streamReader.Close();
            webResponse.Close();

            return response;  //返回结果
        }


        public static string GetUrl(string url, List<KeyValuePair<string, string>> headers)
        {

            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                System.Console.WriteLine("https connections.....");
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                // 这里设置了协议类型。
                //ServicePointManager.SecurityProtocol =SecurityProtocolType.Tls12;// (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //(SecurityProtocolType)768 | (SecurityProtocolType)3072

                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //增加下面两个属性即可  
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;

            request.Method = "GET";    //使用get方式发送数据
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = "";
            request.AllowAutoRedirect = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Accept = "*/*";

            if (headers != null && headers.Count > 0)
            {
                foreach (var item in headers)
                {
                    request.Headers.Add(item.Key, item.Value);
                }

            }

            //获取网页响应结果
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //Thread.Sleep(2000);
            Stream stream = response.GetResponseStream();
            //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                result = sr.ReadToEnd();
            }

            if (request != null)
            {
                request.Abort();
            }

            if (response != null)
            {
                response.Close();
            }

            return result;
        }


        /// <summary>
        /// 生成签名
        /// </summary>

        /// <returns></returns>
        public string GenerateSign(List<KeyValuePair<string, string>> lst, string privateKey)
        {
            Comparison<KeyValuePair<string, string>> Comparer = new Comparison<KeyValuePair<string, string>>(CompareKeyValuepair);
            lst.Sort(Comparer);
            var paramlst = lst.Where(p => !string.IsNullOrEmpty(p.Value)).ToList();
            string signstr = string.Join("&", paramlst.Select(p => p.Key + "=" + p.Value)).ToLower() + privateKey;
            return Sign(signstr, "UTF-8");
        }

        public string GetParamBeforMD5(List<KeyValuePair<string, string>> lst, string privateKey)
        {
            Comparison<KeyValuePair<string, string>> Comparer = new Comparison<KeyValuePair<string, string>>(CompareKeyValuepair);
            lst.Sort(Comparer);
            var paramlst = lst.Where(p => !string.IsNullOrEmpty(p.Value)).ToList();
            return string.Join("&", paramlst.Select(p => p.Key + "=" + p.Value)).ToLower() + privateKey;

        }


        /// <summary>
        /// 根据Key比较排序位置
        /// </summary>
        private static int CompareKeyValuepair(KeyValuePair<string, string> p1, KeyValuePair<string, string> p2)
        {
            return string.Compare(p1.Key, p2.Key);
        }

        /// <summary>
        /// 签名字符串
        /// </summary>
        /// <param name="prestr">需要签名的字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="inputCharset">编码格式</param>
        /// <returns>签名结果</returns>
        public string Sign(string prestr, string inputCharset)
        {
            StringBuilder sb = new StringBuilder();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(inputCharset).GetBytes(prestr));
            foreach (byte t1 in t)
            {
                sb.Append(t1.ToString("x2"));
            }
            return sb.ToString();
        }

        public void GoToPageFroUnion(string unionId, string unionUserInfo)
        {
            unionId = unionId.ToLower();
            switch (unionId)
            {
                case "puhui":
                    {
                        var phone = GetUserPhoneByPuhuiToken(unionUserInfo);
                     
                        if (!string.IsNullOrWhiteSpace(phone))
                        {
                            phone = Framework.Utilities.EncryptDES(phone);
                            phone = Server.UrlEncode(phone);
                            Response.Redirect($"http://union.xdjsclub.com/home/UnionIndex?fid={phone}&client=puhui&token={unionUserInfo}");
                            //  Response.Redirect($"http://localhost:55567/home/UnionIndex?fid={phone}&client=puhui");
                        }
                        break;


                    }
            }

        }
    }


    #region





    #endregion
}